<template>
  <div>
    <Card>
      <Button type="primary" @click="showAddModal" class="mr10"
        >添加任务</Button
      >
      <Button
        type="primary"
        :loading="refreshLoading"
        @click="refreshEvent"
        shape="circle"
        icon="md-refresh"
        class="fr"
      ></Button>
      <Select v-model="searchTypeValue" class="searchInputClass">
        <Option
          v-for="item in searchType"
          :value="item.value"
          :key="item.value"
          >{{ item.label }}</Option
        >
      </Select>
      <Input
        v-model="searchKeyWord"
        placeholder="请输入搜索关键字"
        suffix="ios-search"
        class="searchKeyWordInputClass"
      />
      <span class="tips"
        >完成情况请输入0或1搜索，0代表未完成，1代表已完成,</span
      >
    </Card>
    <Card>
      <Tables
        ref="tables"
        editable
        v-model="searchData"
        :columns="columns"
        :loading="loading"
        :border="true"
        size="large"
      />
    </Card>
    <Page
      :total="num"
      @on-change="changePage"
      show-sizer
      show-elevator
      show-total
      :page-size="pageSize"
      :page-size-opts="$store.state.pageSizeArray"
      @on-page-size-change="changePageSize"
      style="margin-top: 12px; float: right"
    />
    <Modal
      title="添加任务"
      v-model="addModal"
      :styles="{ top: '50px' }"
      @on-ok="addDataEvent"
    >
      <Form :model="addData" :label-width="80">
        <FormItem label="标题：">
          <Input
            v-model="addData.title"
            maxlength="50"
            type="text"
            placeholder="请输入标题，字数不超过50字。"
          ></Input>
        </FormItem>
        <FormItem label="备注：">
          <Input
            v-model="addData.remarks"
            maxlength="100"
            show-word-limit
            type="textarea"
            placeholder="请输入备注，字数不超过100字。"
            :rows="4"
          ></Input>
        </FormItem>
        <FormItem label="完成情况：">
          <i-switch
            v-model="addData.finished"
            size="large"
            true-value="1"
            false-value="0"
            true-color="#13ce66"
            false-color="#ff4949"
          >
            <span slot="open">完成</span>
            <span slot="close">未完成</span>
          </i-switch>
        </FormItem>
      </Form>
    </Modal>

    <Modal
      title="修改计划"
      v-model="editTodoListModal"
      :styles="{ top: '50px' }"
      @on-ok="editDataEvent"
    >
      <Form :model="editData" :label-width="80">
        <FormItem label="标题：">
          <Input
            v-model="editData.title"
            maxlength="50"
            type="text"
            placeholder="请输入标题，字数不超过50字。"
          ></Input>
        </FormItem>
        <FormItem label="备注：">
          <Input
            v-model="editData.remarks"
            maxlength="100"
            show-word-limit
            type="textarea"
            placeholder="请输入备注，字数不超过100字。"
            :rows="4"
          ></Input>
        </FormItem>
        <FormItem label="完成情况：">
          <i-switch
            v-model="editData.finished"
            size="large"
            true-value="1"
            false-value="0"
            true-color="#13ce66"
            false-color="#ff4949"
          >
            <span slot="open">完成</span>
            <span slot="close">未完成</span>
          </i-switch>
        </FormItem>
      </Form>
    </Modal>
  </div>
</template>

<script>
import Tables from "_c/tables";
import {
  getTodoListData,
  addTodoListData,
  finishTodoList,
  deleteTodoListData,
  editTodoListData,
} from "@/api/content/todolist/index";
export default {
  name: "tables_page",
  components: {
    Tables,
  },
  data() {
    return {
      refreshLoading: false,
      addData: { finished: false, remarks: "", time: "" },
      addModal: false,
      editData: {},
      editTodoListModal: false,
      num: 0,
      columns: [
        { title: "时间", key: "date", sortable: true, width: 200 },
        { title: "标题", key: "title" },
        { title: "内容", key: "remarks" },
        {
          title: "完成情况",
          width: 100,
          render: (h, params) => {
            return h("div", [
              h("i-switch", {
                props: {
                  trueValue: "1",
                  falseValue: "0",
                  value: params.row.finished,
                  trueColor: "#13ce66",
                  falseColor: "#ff4949",
                },
                style: {
                  marginRight: "5px",
                },
                on: {
                  "on-change": (value) => {
                    params.row.finished = value;
                    this.finishEvent(params.row.id, value);
                  },
                },
              }),
            ]);
          },
        },
        {
          title: "操作",
          width: 200,
          align: "center",
          render: (h, params) => {
            return h("div", [
              h(
                "Button",
                {
                  props: {
                    type: "primary",
                  },
                  style: {
                    marginRight: "5px",
                  },
                  on: {
                    click: () => {
                      this.editData = params.row;
                      this.showEditModal();
                    },
                  },
                },
                "修改"
              ),
              h(
                "Poptip",
                {
                  props: {
                    confirm: true,
                    type: "error",
                    size: "large",
                    title: "你确定要删除吗?",
                  },

                  on: {
                    "on-ok": () => {
                      this.deleteDataEvent(params.row);
                    },
                    "on-cancel": () => {
                      this.$Message.info("您取消了删除");
                    },
                  },
                },
                [
                  h(
                    "Button",
                    {
                      props: {
                        type: "warning",
                      },
                      style: {
                        marginRight: "5px",
                      },
                    },
                    "删除"
                  ),
                ]
              ),
            ]);
          },
        },
      ],
      tableData: [],
      num: 0,
      pageCurrent: 1,
      pageSize: 10,
      loading: true,
      searchType: [
        {
          label: "标题",
          value: "title",
        },
        {
          label: "备注",
          value: "remarks",
        },
        {
          label: "完成情况",
          value: "finished",
        },
      ],
      searchTypeValue: "finished",
      searchKeyWord: "",
    };
  },
  methods: {
    //添加任务
    addDataEvent() {
      if (!this.requireFormData(this.addData)) {
        return;
      } else {
        addTodoListData(this.addData).then((res) => {
          if (res.data.code == 0) {
            this.getData(this.pageCurrent, this.pageSize);
            this.addData.time = this.getFormatDate();
            this.$Message.success("您成功添加了一个任务.");
            this.addData = { finished: false };
          } else if (res.data.code == 1010) {
            this.$Message.error("您的登录状态已失效，请您重新登录.");
            this.$router.push("/login");
          } else {
            this.$Message.error("您添加任务失败了，错误原因：" + res.data.msg);
          }
        });
      }
    },
    editDataEvent() {
      if (!this.requireFormData(this.addData)) {
        return;
      } else {
        editTodoListData(this.editData)
          .then((res) => {
            if (res.data.code == 0) {
              this.columns[this.editData._index] = this.editData;
              this.$Message.success("您成功修改了一个任务.");
              this.editData = { finished: false };
            } else if (res.data.code == 1010) {
              this.$Message.warning("您的登录状态已失效，请您重新登录.");
              this.$router.push("/login");
            } else {
              this.$Message.error(
                "您修改任务失败了，错误原因：" + res.data.msg
              );
            }
          })
          .catch((err) => {
            this.$Message.error("服务器异常，请稍后重试.错误原因：" + err);
          });
      }
    },
    requireFormData(data) {
      if (!data.title || data.title.length < 50) {
        this.$Message.warning(
          "您输入的标题错误，字数在1-50位之间，请重新输入."
        );
        return false;
      } else if (!data.remarks || data.remarks.length > 100) {
        this.$Message.warning(
          "您输入的内容格式错误，字数在1-100位之间，请重新输入."
        );
        return false;
      } else {
        return true;
      }
    },
    getFormatDate() {
      var date = new Date();
      var month = date.getMonth() + 1;
      var strDate = date.getDate();
      if (month >= 1 && month <= 9) {
        month = "0" + month;
      }
      if (strDate >= 0 && strDate <= 9) {
        strDate = "0" + strDate;
      }
      var currentDate =
        date.getFullYear() +
        "-" +
        month +
        "-" +
        strDate +
        " " +
        date.getHours() +
        ":" +
        date.getMinutes() +
        ":" +
        date.getSeconds();
      return currentDate;
    },
    //删除任务
    deleteDataEvent(row) {
      deleteTodoListData(row.id)
        .then((res) => {
          if (res.data.code == 0) {
            this.tableData.splice(row["_index"], 1);
            this.$Message.success("您成功删除了一个任务.");
          } else if (res.data.code == 1010) {
            this.$Message.warning("您的登录状态已失效，请您重新登录.");
            this.$router.push("/login");
          } else {
            this.$Message.error("您删除任务失败了，错误原因：" + res.data.msg);
          }
        })
        .catch((err) => {
          this.$Message.error("服务器异常，请稍后重试.错误原因：" + err);
        });
    },
    refreshEvent() {
      this.refreshLoading = true;
      this.getData(this.pageCurrent, this.pageSize);
    },
    //打开添加页面
    showAddModal() {
      this.addModal = true;
    },

    //打开修改页面
    showEditModal() {
      this.editTodoListModal = true;
    },
    //完成任务
    finishEvent(id, value) {
      finishTodoList(id, value)
        .then((res) => {
          if (res.data.code == 0) {
            value == 1
              ? this.$Message.success("任务状态已变更：任务已完成.")
              : this.$Message.info("任务状态已变更：任务未完成.");
          } else if (res.data.code == 1010) {
            this.$Message.warning("您的登录状态已失效，请您重新登录.");
            this.$router.push("/login");
          }
        })
        .catch((err) => {
          this.$Message.error("服务器异常，请稍后重试.错误原因：" + err);
        });
    },

    //获取表格任务
    getData(page, pageNum) {
      this.loading = true;
      getTodoListData(page, pageNum)
        .then((res) => {
          if (res.data.code == 0) {
            this.num = res.data.num;
            this.tableData = res.data.data;
            this.loading = false;
            this.refreshLoading = false;
          } else if (res.data.code == 1010) {
            this.$Message.warning("您的登录状态已失效，请您重新登录.");
            this.$router.push("/login");
          } else {
            this.$Message.error(
              "自动获取数据失败了，错误原因：" + res.data.msg
            );
          }
        })
        .catch((err) => {
          this.$Message.error("服务器异常，请稍后重试.错误原因：" + err);
        });
    },

    //第几页任务
    changePage(index) {
      this.pageCurrent = index;
      this.getData(this.pageCurrent, this.pageSize);
    },

    //每页显示任务
    changePageSize(size) {
      this.pageSize = size;
      this.getData(this.pageCurrent, this.pageSize);
    },
  },
  created() {
    this.pageSize = this.$store.state.pageSize;
    this.getData(this.pageCurrent, this.pageSize);
  },
  computed: {
    searchData() {
      if (!this.searchKeyWord) {
        return this.tableData;
      }
      return this.tableData.filter((item) => {
        return item[this.searchTypeValue].indexOf(this.searchKeyWord) !== -1;
      });
    },
  },
};
</script>